// Includes
#include "FileHelpers.h"

#include <fstream>		// C++ file stream library
#include <cstring>		// C string library
#include <iostream>		// C++ I/O stream library

using namespace std;

// Determine if a file exists
bool FileExists(const char *fileName)
{
	// Input file stream object
	ifstream inputStream;
	// Attempt to open file
	inputStream.open(fileName);
	
	// Check fail bit to determine if file was opened
	return !inputStream.fail();
}

// Creates a file
int CreateFile(const char *fileName)
{
	// Output file stream
	ofstream outputStream;
	// Open stream
	outputStream.open(fileName);
	
	// Check if file is open
	if (!outputStream.is_open())
		// Return error if not
		return 1;
	// Check fail bit of stream
	if (outputStream.fail())
		// Return error
		return 2;

	// Close stream
	outputStream.close();
	// Return successfully
	return 0;
}

// Loads a file into memory
unsigned int LoadFileToMemory(const char *fileName, char **dest)
{
	// Check if file exists
	if (!FileExists(fileName))
	{
		cout << "Error: File " << fileName << " does not seem to exist." << endl;
		return 0;
	}	
		
	// Create file stream
	fstream fileStream;
	// Open file
	fileStream.open(fileName, fstream::in | fstream::binary);
	
	// Check if file was opened correctly
	if (!fileStream.is_open())
	{
		cout << "Error: Failed to open file " << fileName << endl;
		return 0;
	}
		
	// Move get pointer to end of stream
	fileStream.seekg(0, ios::end);
	// Get length of file in bytes
	unsigned int length = fileStream.tellg();
	
	// Allocate memory for file
	*dest = new char[length];
	
	// Move get pointer to beginning of stream
	fileStream.seekg(0, ios::beg);
	
	// Read data to buffer
	fileStream.read(*dest, length);
	
	// Close file stream
	fileStream.close();
	
	// Return size of file
	return length;
}
